package com.itheima.controller;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.constant.TokenConstant;
import com.itheima.pojo.Employee;
import com.itheima.service.EmployeeService;
import com.itheima.vo.EmployeeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 */
@Slf4j
@RestController
@RequestMapping("employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 添加员工
     * @param employee
     * @return
     */
    @PostMapping("")
    public R<String> save(@RequestBody Employee employee,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Object o = redisTemplate.opsForValue().get(TokenConstant.EMPLOYEE_TOKEN_PREFIX + token);
        if (Objects.nonNull(o)) {
            Employee emp = JSON.parseObject((String) o, Employee.class);
            System.out.println(token);
            employee.setUpdateUser(emp.getId());
            employee.setCreateUser(emp.getId());

            Boolean res = employeeService.addEmployee(employee);

            return R.success("新增员工成功");
        }
        return R.error("请登录后操作");
    }

    /**
     * 修改信息
     * @param employee
     * @return
     */
    @PutMapping("")
    public R<String> modifyEmployee(@RequestBody Employee employee){

        employeeService.modifyEmployee(employee);

        return R.success("修改成功");
    }

    /**
     * 分页查询
     * @param request
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("page")
    public R<Page> page(HttpServletRequest request,
                        @RequestParam(value = "page",defaultValue = "0") int page,
                        @RequestParam(value = "pageSize",defaultValue = "10") int pageSize,
                        @RequestParam(required = false)String name
                        ){

        Page<Employee> pageInfo = employeeService.getPage(page, pageSize, name);
        return R.success(pageInfo);
    }

    /**
     * 登录
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<EmployeeVo> employeeLogin(@RequestBody Employee employee){

        String password = employee.getPassword();
        password= DigestUtils.md5DigestAsHex(password.getBytes());
        Employee emp = employeeService.employeeLogin(employee.getUsername(), password);

        if(Objects.isNull(emp)){
            return R.error("账号密码错误,或账号已停用");
        }

        String tokenString = System.currentTimeMillis() + emp.getId();
        String token = DigestUtils.md5DigestAsHex(tokenString.getBytes());

        redisTemplate.opsForValue().set(TokenConstant.EMPLOYEE_TOKEN_PREFIX+token, JSON.toJSONString(emp),259200, TimeUnit.SECONDS);

        EmployeeVo employeeVo = new EmployeeVo();
        BeanUtils.copyProperties(emp,employeeVo);
        employeeVo.setToken(token);
        return R.success(employeeVo);
    }

    /**
     * 退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){


        String token = request.getHeader("Authorization");
        redisTemplate.delete(token);
        return R.success("退出成功");
    }


    @GetMapping( "/{id}")
    public R<Employee> getById(@PathVariable String id){

        Employee employee = employeeService.getById(id);
        if(Objects.nonNull(employee)){
            return R.success(employee);
        }
     return R.error("没有查询到员工信息");
    }
}
